import 'package:HnXG/Api.dart';
import 'package:HnXG/Request/Request5.dart';
import 'package:HnXG/Request/Request6.dart';
import 'package:flutter/material.dart';


class MaterialListPage extends StatefulWidget {

  const MaterialListPage({super.key});
  @override
  _MaterialListPageState createState() => _MaterialListPageState();

}

class _MaterialListPageState extends State<MaterialListPage> {
  // 新增搜索控制器
  final TextEditingController _searchController = TextEditingController();

  // 预留数据变量
  List<Map<String, dynamic>> materials = [];

  final TextEditingController _materialIdController = TextEditingController();
  final TextEditingController _warehouseController = TextEditingController();
  final TextEditingController _descriptionController = TextEditingController();

  @override
  void dispose() {
    _searchController.dispose();
    _materialIdController.dispose();
    _warehouseController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    Api.GetMaterialList(Request6(MaterialList_Name: '')).then((response) {
      if (response['state'] == true) {
        setState(() {
          materials = List<Map<String, dynamic>>.from(
              response['dto'].map((x) => x as Map<String, dynamic>));
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('物料清单', 
          style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
        leading: SizedBox.shrink(),
        centerTitle: true,
        backgroundColor: Colors.blue,
        elevation: 3,
      ),
      body: Column(
        children: [
          // 搜索区
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _searchController,
                    decoration: InputDecoration(
                      hintText: '输入物料名称搜索',
                      border: OutlineInputBorder(),
                    ),
                  ),
                ),
                ElevatedButton(
                  onPressed: () async {
                    final response = await Api.GetMaterialList(Request6(MaterialList_Name: _searchController.text));
                    if(response['state']==true){
                      setState(() {
                        materials = List<Map<String,dynamic>>.from(response['dto'].map((x) => x as Map<String,dynamic>));
                      });
                    }
                  },
                  child: Text('搜索'),
                ),
                SizedBox(width: 12),
                ElevatedButton(
                  onPressed: () {
                    showDialog(
                      context: context,
                      builder: (context) => AlertDialog(
                        title: Text('添加新物料'),
                        content: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            TextField(
                              controller: _materialIdController,
                              decoration: InputDecoration(labelText: '物料号'),
                            ),
                            TextField(
                              controller: _warehouseController,
                              decoration: InputDecoration(labelText: '目标仓库'),
                            ),
                            TextField(
                              controller: _descriptionController,
                              decoration: InputDecoration(labelText: '描述'),
                            ),
                          ],
                        ),
                        actions: [
                          TextButton(
                            onPressed: () => Navigator.pop(context),
                            child: Text('取消'),
                          ),
                          ElevatedButton(
                            onPressed: () async {
                              if (_materialIdController.text.isEmpty) {
                                ScaffoldMessenger.of(context).showSnackBar(
                                  SnackBar(content: Text('物料号不能为空'))
                                );
                                return;
                              }
                              final response = await Api.CreateMaterialList(Request5(
                                MaterialList_Name: _materialIdController.text,
                                Target: _warehouseController.text,
                                Description: _descriptionController.text
                              ));
                              Navigator.pop(context);
                              if (response['state'] == true) {
 
                                _materialIdController.clear();
                                _warehouseController.clear();
                                _descriptionController.clear();
                              }
                              ScaffoldMessenger.of(context).showSnackBar(
                                SnackBar(content: Text(response['msg'] ?? (response['state'] ? '添加成功' : '添加失败')))
                              );
                            },
                            child: Text('确认'),
                          ),
                        ],
                      ),
                    );
                  },
                  child: Text('+ 添加物料'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.green,
                  ),
                ),
              ],
            ),
          ),

          // 数据列表
          Expanded(
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 16),
                  child: Row(
                    children: [
                      Expanded(
                        flex: 1,
                        child: Text('序号', style: TextStyle(fontWeight: FontWeight.bold)),
                      ),
                      Expanded(
                        flex: 3,  // 从3调整为2
                        child: Text('物料号', style: TextStyle(fontWeight: FontWeight.bold)),
                      ),
                      Expanded(
                        flex: 2,  // 从1调整为2
                        child: Text('目标仓库', style: TextStyle(fontWeight: FontWeight.bold)),
                      ),
                      Expanded(
                        flex: 2,
                        child: Text('描述', style: TextStyle(fontWeight: FontWeight.bold)),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: ListView.builder(
                    itemCount: materials.length,
                    itemBuilder: (context, index) {
                      return ListTile(
                        title: Row(
                          children: [
                            Expanded(
                              flex: 1,
                              child: Text((index + 1).toString()),
                            ),
                            Expanded(
                              flex: 3,  // 从3调整为2
                              child: Text(materials[index]['materialList_Name'] ?? ''),
                            ),
                            Expanded(
                              flex: 2,  // 从1调整为2
                              child: Text(materials[index]['target'] ?? ''),
                            ),
                            Expanded(
                              flex: 2,
                              child: Text(
                                materials[index]['description'] ?? '',
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}